<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>小红书/抖音爆文检索</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body class="bg-gray-100">
    <!-- 图片预览模态框 -->
    <div id="imageModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden flex items-center justify-center">
        <div class="relative max-w-2xl w-full mx-4">
            <img id="modalImage" src="" alt="预览图片" class="w-full h-auto max-h-[80vh] object-contain rounded-lg">
            <button onclick="closeImageModal()" class="absolute top-4 right-4 text-white hover:text-gray-300">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                </svg>
            </button>
        </div>
    </div>
    <div class="container mx-auto px-4 py-8">
        <!-- 顶部搜索栏 -->
        <div class="flex justify-between items-center mb-8">
            <h1 class="text-3xl font-bold text-red-500">小红书/抖音爆文检索</h1>
            <div class="flex items-center gap-4">
                <div class="relative flex gap-2">
                    <input 
                        type="text" 
                        id="searchInput"
                        placeholder="点搜索获取爆文➡️..." 
                        class="px-4 py-2 border rounded-lg focus:outline-none focus:border-red-500"
                    >
                    <button 
                        onclick="handleSearch()"
                        class="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition duration-200"
                    >
                        搜索
                    </button>
                </div>
                <a href="/login" class="text-red-500 hover:text-red-600">
                    进入管理后台
                </a>
            </div>
        </div>

        <!-- 功能说明板块 -->
        <div class="bg-white p-6 rounded-lg shadow mb-8">
            <h2 class="text-xl font-semibold mb-4 text-gray-800">功能说明</h2>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div class="p-4 border rounded-lg bg-gray-50">
                    <h3 class="font-medium text-blue-600 mb-2">搜索功能</h3>
                    <p class="text-gray-600 text-sm">点击"搜索"↗️获取最新爆文，支持按地区和关键词</p>
                </div>
                <div class="p-4 border rounded-lg bg-gray-50">
                    <h3 class="font-medium text-green-600 mb-2">复制改写</h3>
                    <p class="text-gray-600 text-sm">生成提示词到 <a class="text-blue-500" href="https://coze.cn" target="_blank">coze</a>/<a class="text-blue-500" href="https://kimi.ai" target="_blank">kimi</a> 改写</p>
                </div>
                <div class="p-4 border rounded-lg bg-gray-50">
                    <h3 class="font-medium text-red-600 mb-2">爆款标记</h3>
                    <p class="text-gray-600 text-sm">特别标记热门爆款文章</p>
                </div>
            </div>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
            <!-- 地区选择 -->
            <div class="bg-white p-4 rounded-lg shadow">
                <h2 class="text-xl font-semibold mb-4">选择地区</h2>
                <div class="space-y-2" id="districtList">
                    {% for district, locations in locations.items() %}
                    <button 
                        id="district-{{ district }}"
                        onclick="selectDistrict('{{ district }}')"
                        class="px-3 py-1 text-sm rounded-full border hover:border-red-500 hover:text-red-500 transition-colors"
                    >
                        {{ district }}
                    </button>
                    {% endfor %}
                </div>
                <div id="locationsList" class="hidden mt-4">
                    <div id="locationsContainer"></div>
                </div>
            </div>

            <!-- 文章列表 -->
            <div class="bg-white p-6 rounded-lg shadow md:col-span-3">
                <div class="flex justify-between items-center mb-6">
                    <h2 class="text-xl font-semibold text-gray-800">文章列表</h2>
                </div>
                <div id="postsList" class="space-y-6 max-h-[600px] overflow-y-auto">
                    <!-- 文章将通过 JavaScript 动态添加到这里 -->
                </div>
            </div>
        </div>
    </div>

    <script>
        let selectedDistrict = '';
        let selectedLocation = '';

        function selectDistrict(district) {
            // 移除之前选中的区域样式
            if (selectedDistrict) {
                const prevButton = document.getElementById(`district-${selectedDistrict}`);
                if (prevButton) {
                    prevButton.classList.remove('border-red-500', 'text-red-500');
                }
            }
            
            // 清除之前选中的地点
            if (selectedLocation) {
                const locButton = document.getElementById(`location-${selectedLocation}`);
                if (locButton) {
                    locButton.classList.remove('border-red-500', 'text-red-500');
                }
                selectedLocation = '';
            }
            
            // 如果点击已选中的区域，则取消选择
            if (selectedDistrict === district) {
                selectedDistrict = '';
                document.getElementById('locationsList').classList.add('hidden');
            } else {
                // 选中新区域
                selectedDistrict = district;
                const button = document.getElementById(`district-${district}`);
                button.classList.add('border-red-500', 'text-red-500');
                
                // 显示并更新地点列表
                updateLocations(district);
            }
            
            handleSearch();
        }

        function updateLocations(district) {
            const locationsList = document.getElementById('locationsList');
            const locationsContainer = document.getElementById('locationsContainer');
            
            // 清空并更新地点列表
            locationsContainer.innerHTML = '';
            {% for district_name, locations in locations.items() %}
            if (district === '{{ district_name }}') {
                {% for location in locations %}
                const btn = document.createElement('button');
                btn.textContent = '{{ location }}';
                btn.id = `location-{{ location }}`;
                btn.onclick = () => selectLocation('{{ location }}');
                btn.className = 'px-3 py-1 text-sm rounded-full border hover:border-red-500 hover:text-red-500 transition-colors';
                locationsContainer.appendChild(btn);
                {% endfor %}
            }
            {% endfor %}
            
            locationsList.classList.remove('hidden');
        }

        function selectLocation(location) {
            // 移除之前选中的地点样式
            if (selectedLocation) {
                const prevButton = document.getElementById(`location-${selectedLocation}`);
                if (prevButton) {
                    prevButton.classList.remove('border-red-500', 'text-red-500');
                }
            }
            
            // 如果点击已选中的地点，则取消选择
            if (selectedLocation === location) {
                selectedLocation = '';
            } else {
                selectedLocation = location;
                const button = document.getElementById(`location-${location}`);
                button.classList.add('border-red-500', 'text-red-500');
            }
            
            handleSearch();
        }

        function handleSearch() {
            const keyword = document.getElementById('searchInput').value;
            const params = new URLSearchParams();
            
            if (keyword) {
                params.append('keyword', keyword);
            }
            
            // 优先使用选中的地点，如果没有则使用选中的区域
            if (selectedLocation) {
                params.append('location', selectedLocation);
            } else if (selectedDistrict) {
                params.append('location', selectedDistrict);
            }
            
            // 保持原有的搜索请求格式
            axios.get(`/api/search?${params.toString()}`)
                .then(response => {
                    displayPosts(response.data);
                })
                .catch(error => {
                    console.error('搜索失败:', error);
                    alert('搜索失败，请稍后重试');
                });
        }

        function displayPosts(posts) {
            const postsContainer = document.getElementById('postsList');
            if (posts.length === 0) {
                postsContainer.innerHTML = '<div class="text-gray-500 text-center py-8">暂无相关文章</div>';
                return;
            }

            postsContainer.innerHTML = posts.map(post => {
                // 预处理文本，避免 JavaScript 字符串问题
                const escapedTitle = post.title.replace(/'/g, "\\'").replace(/"/g, '\\"');
                const escapedContent = post.content.replace(/'/g, "\\'").replace(/"/g, '\\"').replace(/`/g, '\\`');
                
                return `
                <div class="group p-6 border border-gray-200 rounded-lg hover:border-red-200 hover:shadow-md transition-all duration-200">
                    <div class="flex gap-6">
                        <div class="flex-shrink-0">
                            <img src="${post.cover.startsWith('/static/images/') ? 
                                      post.cover : 
                                      `https://images.weserv.nl/?url=${encodeURIComponent(post.cover)}`}" 
                                 class="w-32 h-32 object-cover rounded-lg cursor-pointer hover:opacity-90 transition-opacity"
                                 onclick="openImageModal(this.src)"
                                 alt="文章封面">
                        </div>
                        <div class="flex-grow min-w-0">
                            <div class="flex justify-between items-start mb-3">
                                <div class="flex items-center gap-2 min-w-0">
                                    <h3 class="font-semibold text-lg text-gray-900 truncate">${post.title}</h3>
                                    <button onclick="copyToClipboard('${escapedTitle}')" 
                                            class="flex-shrink-0 text-gray-400 hover:text-gray-600 p-1 rounded-full hover:bg-gray-100 transition-colors"
                                            title="复制标题">
                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3"/>
                                        </svg>
                                    </button>
                                    ${post.is_hot ? '<span class="text-red-500 text-sm font-medium ml-2">爆款</span>' : ''}
                                </div>
                                <div class="text-sm text-gray-500">${post.created_at || ''}</div>
                            </div>
                            <p class="text-gray-600 text-sm mb-3 line-clamp-2">${post.content}</p>
                            <div class="flex items-center justify-between">
                                <div class="flex items-center gap-4">
                                    ${post.location ? `<span class="text-sm text-gray-500">📍 ${post.location}</span>` : ''}
                                    ${post.interaction ? `
                                    <div class="flex items-center gap-2 text-sm text-gray-500">
                                        <span>❤️ ${post.interaction}</span>
                                    </div>` : ''}
                                </div>
                                <div class="flex items-center gap-2">
                                    <a href="${post.url}" target="_blank" 
                                       class="text-red-500 hover:text-red-600 text-sm">
                                        查看原文
                                    </a>
                                    <button onclick="copyToClipboard('${escapedContent}')"
                                            class="text-gray-500 hover:text-gray-600 text-sm">
                                        复制正文
                                    </button>
                                    <button onclick="copyToClipboard(\`请帮我改写以下文章，保持原意但措辞和语言表达要不同：\n\n${escapedContent}\`)"
                                            class="text-blue-500 hover:text-blue-600 text-sm">
                                        复制改写
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `}).join('');
        }

        function copyToClipboard(text) {
            // 创建一个临时的 textarea 元素
            const textarea = document.createElement('textarea');
            textarea.value = text;
            textarea.style.position = 'fixed';
            textarea.style.opacity = '0';
            document.body.appendChild(textarea);
            
            // 选择文本并复制
            textarea.select();
            try {
                document.execCommand('copy');
                alert('复制成功！');
            } catch (err) {
                console.error('复制失败:', err);
                // 如果 execCommand 失败，尝试使用 clipboard API
                navigator.clipboard.writeText(text)
                    .then(() => alert('复制成功！'))
                    .catch(err => {
                        console.error('复制失败:', err);
                        alert('复制失败，请手动复制');
                    });
            } finally {
                document.body.removeChild(textarea);
            }
        }

        function openImageModal(src) {
            const modal = document.getElementById('imageModal');
            const modalImage = document.getElementById('modalImage');
            modalImage.src = src;
            modal.classList.remove('hidden');
            // 禁止背景滚动
            document.body.style.overflow = 'hidden';
        }

        function closeImageModal() {
            const modal = document.getElementById('imageModal');
            modal.classList.add('hidden');
            // 恢复背景滚动
            document.body.style.overflow = '';
        }

        // 点击模态框背景关闭
        document.getElementById('imageModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeImageModal();
            }
        });

        // ESC键关闭模态框
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                closeImageModal();
            }
        });

        // 页面加载时获取最新文章
        window.onload = function() {
            handleSearch();
        };

        // 监听回车键
        document.getElementById('searchInput').addEventListener('keyup', function(event) {
            if (event.key === 'Enter') {
                handleSearch();
            }
        });
    </script>
</body>
</html>
